package com.eco.fanliapp.job.redmoneyjob;

import com.eco.fanliapp.common.constant.NewsEnumLog;
import com.eco.fanliapp.entity.AppUserRedReward;
import com.eco.fanliapp.entity.AppUserRewardSetup;
import com.eco.fanliapp.entity.SyUserMoney;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.DateFormatUtils;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 定时领取邀请赚钱红包
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class ReceiveInvitationRedMoney implements Job, Serializable {


    private static final Logger log = LoggerFactory.getLogger(ReceiveInvitationRedMoney.class);

    @Autowired
    private IAppUserRedRewardService appUserRedRewardService;
    @Autowired
    private IAppNewsLogService iAppNewsLogService;
    @Autowired
    private UpdateUserCommon updateUserCommon;
    @Autowired
    private IAppUserRewardSetupService iAppUserRewardSetupService;
    @Autowired
    private ISyUserMoneyLogService syUserMoneyLogService;
    @Autowired
    private ISyUserMoneyService iSyUserMoneyService;

    public ReceiveInvitationRedMoney() {
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap =  jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long startTime = System.currentTimeMillis();
        log.info("***************************************开始执行定时领取邀请赚钱红包任务-ReceiveInvitationRedMoney：executeCount="+executeCount+"--startTime="+startTime);
        try {
            //查询红包表的数据
            Long stime = DateFormatUtils.getStartTime();
            Long etime = DateFormatUtils.getEndTime();
            List<AppUserRedReward> appUserRedRewardList = appUserRedRewardService.selectAppUserRedReward(stime,etime);
            if(appUserRedRewardList != null){
                for (AppUserRedReward appUserRedReward : appUserRedRewardList) {
                    //更新红包状态
                    appUserRedReward.setExpireTime(new Date().getTime());
                    appUserRedReward.setUpdateTime(new Date().getTime());
                    int i = appUserRedRewardService.updateReceiveHbStatus(appUserRedReward);
                    if (i > 0) {
                        // TODO: 红包结算金额修改
                        int ktx = updateUserCommon.UpdateUserMoney(appUserRedReward.getHbMoney(), appUserRedReward.getUserId(), 5);//好友首次购物
                        if (ktx <= 0){
                            log.info("更新余额失败");
                        }else {
                            //首次查询用户钱中是否存在数据
                            SyUserMoney oldSyUserMoney = iSyUserMoneyService.selectByUserId(appUserRedReward.getUserId());
                            log.info("用户提取红包金额到用户余额成功用户id{}红包金额{}", appUserRedReward.getUserId(), appUserRedReward.getHbMoney());
                            //增加一条消息记录
                            iAppNewsLogService.newsType(appUserRedReward.getUserId(), NewsEnumLog.NEWS_FIRST_FENS.getNewsType(), appUserRedReward.getHbMoney(), appUserRedReward.getHbMoney().toString());
                            log.info("提取成功");

                            BigDecimal cashBalanceAmount = new BigDecimal(0);
                            if(oldSyUserMoney !=null){
                                cashBalanceAmount = oldSyUserMoney.getCashBalanceAmount();
                            }
                            //账户金额发生变动，添加账户变更日志
                            String remark = "邀请赚钱红包到账";
                            Integer logStatus = 0;//加钱
                            syUserMoneyLogService.addSyUserMoneyLog(appUserRedReward.getUserId(),cashBalanceAmount,appUserRedReward.getHbMoney(),remark,null,logStatus);

                        }
                    } else log.info("红包修改状态失败原因：" + "未到提取日期");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.info("领取邀请赚钱红包任务错误");
        }

        long endTime = System.currentTimeMillis();
        log.info("***************************************结束执行定时领取邀请赚钱红包任务-ReceiveInvitationRedMoney：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - startTime));
    }
}
